<template>
  <view class="select-specifications" v-show="isShowSelectSpecifications" @click="cancelSelectSpecifications">
    <view class="content" @click.prevent="() => {}">
      <view class="dish-name">{{ props.dish?.name }}</view>
      <view class="content-rol">
        <view class="choose-dish-flavor">
          <view class="dish-flavor-item" v-for="(flavorItem, index) in props.dish?.dishFlavorList" :key="index">
            <span class="name">{{ flavorItem.name }}</span>
            <view class="value">
              <span
                class="option"
                v-for="(flavorValue, i) in flavorItem.value.split(',')"
                :key="i"
                :class="{ active: isFlavorActive(flavorItem.id, flavorValue) }"
                @click="clickFlavor(flavorItem.id, flavorValue)"
                >{{ Flavor.parse(flavorValue).name }}</span
              >
            </view>
          </view>
        </view>
      </view>
      <view class="buy-quantity">
        <view>份数: {{ cartItem.count }}</view>
        <view class="quantity-control">
          <span class="button down" @click="countPlusOrDown(-1)">-</span>
          <span class="button plus" @click="countPlusOrDown(1)">+</span>
        </view>
      </view>
      <view class="show-and-control">
        <view class="price"
          >总计: <span class="price-value">￥{{ (dishPrice * cartItem.count).toFixed(2) }}</span></view
        >
        <view class="add-to-cart" @click="addToCart">+ 加入购物单</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import Dish from '@/types/entity/Dish'
import type { DishFlavor } from '@/types/entity/DishFlavor'
import { ref, watch } from 'vue'
import { CartItem, Flavor, FlavorNameObj } from '@/types/entity/ShoppingCart'
const props = defineProps({
  dish: {
    type: Dish,
    require: true
  }
})

const emits = defineEmits<{
  (e: 'add-to-cart', cartItem: CartItem): void
  (e: 'update:dish', dish: Dish | undefined): void
}>()
// 是否显示窗口
const isShowSelectSpecifications = ref(false)
// 提交的cartItem
const cartItem = ref(new CartItem())
// 数量加减
function countPlusOrDown(num: number) {
  const newCount = cartItem.value.count + num
  cartItem.value.count = newCount < 1 ? 1 : newCount
}
// 监听变量，弹出规格选择窗口
watch(
  () => props.dish,
  (newDish) => {
    if (newDish == null) return
    // 弹出窗口
    isShowSelectSpecifications.value = true
    // 设置默认选中
    setDefaultFlavorForm(newDish)
    cartItem.value = new CartItem()
    cartItem.value.count = 1
  }
)
// 关闭窗口
function cancelSelectSpecifications() {
  emits('update:dish', undefined)
  isShowSelectSpecifications.value = false
}

// const flavorForm = ref<FlavorFormItem[]>()
// interface FlavorFormItem {
//   id: number
//   name: string
//   price: number
// }

// function getFlavorName() {}
// function getFlavorAppreciation() {}
function isFlavorActive(flavorId: number, flavorName: string) {
  if (flavorForm.value == null || flavorForm.value.length === 0) return false
  for (let flavorFormItem of flavorForm.value) {
    if (flavorFormItem.id === flavorId && flavorFormItem.name === Flavor.parse(flavorName).name) return true
  }
  return false
}

// function addOrChooseSpecifications(dish: Dish) {
//   if (dish == null) return
//   if (dish.dishFlavorList == null || dish.dishFlavorList.length === 0) {
//     // 直接添加
//     return
//   }
//   // 显示规格信息选择
//   currentSpecificationsDish.value = dish
//   isShowSelectSpecifications.value = true
//   // 口味表单，默认选择
//   setDefaultFlavorForm(dish)
// }

// 口味表单值
const flavorForm = ref<Flavor[]>()
// 设置默认的口味表单值
function setDefaultFlavorForm(dish: Dish): void {
  const flavors: DishFlavor[] = dish.dishFlavorList
  if (dish == null || flavors == null || flavors.length === 0) return
  flavorForm.value = flavors.map((flavor) => {
    const minimumPriceFlavor = FlavorNameObj.getMinimumPriceFlavor(flavor.value)
    return {
      id: flavor.id,
      name: minimumPriceFlavor!.name,
      appreciation: minimumPriceFlavor!.price
    }
  })
}

// 动态计算价格
const dishPrice = ref<number>(0)
watch(
  () => flavorForm.value,
  () => refreshDishPrice(),
  { immediate: true, deep: true }
)
function refreshDishPrice(): number {
  if (props.dish == null) return 0
  const basePrice = props.dish!.nowPrice ?? 0
  let appreciationSum = 0
  // 计算选择的菜品的增值
  if (flavorForm.value == null) return basePrice
  flavorForm.value!.forEach((flavor) => (appreciationSum += flavor.appreciation ?? 0))
  return (dishPrice.value = basePrice + appreciationSum)
}

// 点击口味
function clickFlavor(dishId: number, flavorNameAndAppreciation: string) {
  const dishFormItem = flavorForm.value!.find((flavor) => flavor.id === dishId)
  if (dishFormItem == null) return
  const { name, appreciation } = Flavor.parse(flavorNameAndAppreciation)
  dishFormItem.name = name
  dishFormItem.appreciation = appreciation ?? 0
}

// 加入购物车
function addToCart() {
  if (props.dish == null || props.dish.id == null) return
  cartItem.value.id = props.dish!.id
  cartItem.value.price = dishPrice.value
  cartItem.value.flavors = flavorForm.value
  emits('add-to-cart', cartItem.value)
  cancelSelectSpecifications()
}
</script>

<style scoped lang="scss">
.select-specifications {
  position: fixed;
  inset: 0;
  z-index: 1000;
  background-color: #48484859;

  .content {
    $padding-size: 30rpx;

    position: absolute;
    top: 50%;
    left: 50%;
    display: flex;
    justify-content: space-between;
    width: 90%;
    height: 48%;
    border-radius: 30rpx;
    background-color: #fff;
    transform: translate(-50%, -50%);
    box-sizing: border-box;
    flex-direction: column;

    .dish-name {
      padding: $padding-size $padding-size $padding-size * 0.6;
      font-size: 45rpx;
      font-weight: 700;
    }

    .content-rol {
      flex-grow: 1;

      .choose-dish-flavor {
        padding: 0 $padding-size $padding-size;
        width: 100%;
        box-sizing: border-box;

        .dish-flavor-item {
          width: 100%;

          .name {
            line-height: 40rpx;
            height: 40rpx;
            font-size: 35rpx;
          }

          .value {
            width: 100%;
            height: 80rpx;
            line-height: 80rpx;

            .option {
              margin-right: 15rpx;
              padding: 14rpx 25rpx;
              font-size: 28rpx;
              border-radius: 8rpx;
              color: rgb(67 67 67);
              background-color: #ececec;
            }

            .active {
              background-color: #f9d450;
            }
          }
        }
      }
    }

    .buy-quantity {
      $space-between-height: 70rpx;

      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 $padding-size;
      width: 100%;
      height: $space-between-height;
      font-size: 32rpx;
      background-color: #fdfbfe;
      line-height: $space-between-height;
      box-sizing: border-box;

      .quantity-control {
        display: flex;
        justify-content: space-between;

        .button {
          display: block;
          margin-left: 25rpx;
          width: $space-between-height * 0.82;
          height: $space-between-height * 0.82;
          font-weight: 700;
          text-align: center;
          background-color: rgb(236 236 236);
          line-height: $space-between-height * 0.82;
        }
      }
    }

    .show-and-control {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 $padding-size;
      height: 100rpx;
      border-top: 1px solid #d3d3d3;
      line-height: 80rpx;

      .price {
        .price-value {
          color: #fa4d2a;
        }
      }

      .add-to-cart {
        padding: 0 15rpx;
        height: 55rpx;
        font-size: 26rpx;
        font-weight: 700;
        border-radius: 10rpx;
        background-color: #f9d450;
        line-height: 55rpx;
        box-sizing: border-box;
      }
    }
  }
}
</style>
